package com.ruoyi.zsyh.controller;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.EmailUtil;
import com.ruoyi.common.utils.EmptyUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.zsyh.domain.ZsyhPartsQrcode;
import com.ruoyi.zsyh.domain.ZsyhPlatformParts;
import com.ruoyi.zsyh.domain.ZsyhPlatformPartsattribute;
import com.ruoyi.zsyh.service.IZsyhPartsQrcodeService;
import com.ruoyi.zsyh.service.IZsyhPlatformPartsService;
import com.ruoyi.zsyh.service.IZsyhPlatformPartsattributeService;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.zsyh.domain.ZsyhPartsQrcodeHistory;
import com.ruoyi.zsyh.service.IZsyhPartsQrcodeHistoryService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 产品二维码申请记录Controller
 * 
 * @author yuexl
 * @date 2022-01-09
 */
@Controller
@RequestMapping("/zsyh/qrcodeHistory")
public class ZsyhPartsQrcodeHistoryController extends BaseController
{
    private String prefix = "zsyh/qrcodeHistory";

    @Autowired
    private IZsyhPartsQrcodeHistoryService zsyhPartsQrcodeHistoryService;
    @Autowired
    private IZsyhPartsQrcodeService zsyhPartsQrcodeService;
    @Autowired
    private IZsyhPlatformPartsService zsyhPlatformPartsService;
    @Autowired
    private IZsyhPlatformPartsattributeService zsyhPlatformPartsattributeService;

    @RequiresPermissions("zsyh:qrcodeHistory:view")
    @GetMapping()
    public String qrcodeHistory()
    {
        return prefix + "/qrcodeHistory";
    }

    @RequiresPermissions("zsyh:qrcodeHistory:view")
    @GetMapping("/qrcodeApplyCurrent")
    public String qrcodeApplyCurrent()
    {
        return prefix + "/qrcodeApplyCurrent";
    }

    /**
     * 查询产品二维码申请记录列表
     */
    @RequiresPermissions("zsyh:qrcodeHistory:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ZsyhPartsQrcodeHistory zsyhPartsQrcodeHistory)
    {
        startPage();
        List<ZsyhPartsQrcodeHistory> list = zsyhPartsQrcodeHistoryService.selectZsyhPartsQrcodeHistoryList(zsyhPartsQrcodeHistory);
        return getDataTable(list);
    }

    /**
     * 导出产品二维码申请记录列表
     */
    @RequiresPermissions("zsyh:qrcodeHistory:export")
    @Log(title = "产品二维码申请记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ZsyhPartsQrcodeHistory zsyhPartsQrcodeHistory)
    {
        List<ZsyhPartsQrcodeHistory> list = zsyhPartsQrcodeHistoryService.selectZsyhPartsQrcodeHistoryList(zsyhPartsQrcodeHistory);
        ExcelUtil<ZsyhPartsQrcodeHistory> util = new ExcelUtil<ZsyhPartsQrcodeHistory>(ZsyhPartsQrcodeHistory.class);
        return util.exportExcel(list, "产品二维码申请记录数据");
    }

    /**
     * 新增产品二维码申请记录
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存产品二维码申请记录
     */
    @CrossOrigin
    @Transactional
    @RequiresPermissions("zsyh:qrcodeHistory:add")
    @Log(title = "产品二维码申请记录", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ZsyhPartsQrcodeHistory zsyhPartsQrcodeHistory,HttpServletResponse response) throws ParseException, IOException {
        //设置操作人
        zsyhPartsQrcodeHistory.setOperateName(ShiroUtils.getSysUser().getUserName());
        //设置其实编码和结束编码
        zsyhPartsQrcodeHistory.setStartCode(1L);
        zsyhPartsQrcodeHistory.setEndCode(zsyhPartsQrcodeHistory.getApplyNum());
        //设置二维码编码前半部分
        zsyhPartsQrcodeHistory.setQrcodeFirst(String.valueOf(System.currentTimeMillis()) + getRandomCode());
        int num = zsyhPartsQrcodeHistoryService.insertZsyhPartsQrcodeHistory(zsyhPartsQrcodeHistory);
        //在二维码表添加一条记录
        if(num >0){
            ZsyhPartsQrcode zsyhPartsQrcode =  new ZsyhPartsQrcode();
            zsyhPartsQrcode.setQrcodeId(zsyhPartsQrcodeHistory.getQrcodeFirst()+"00000000001");
            zsyhPartsQrcode.setAttributeId(zsyhPartsQrcodeHistory.getAttributeId());
            zsyhPartsQrcode.setPartsId(zsyhPartsQrcodeHistory.getPartsId());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String s = sdf.format(new Date());
            Date date =  sdf.parse(s);
            zsyhPartsQrcode.setProductionDate(date);
            ZsyhPlatformPartsattribute zsyhPlatformPartsattribute = zsyhPlatformPartsattributeService.selectZsyhPlatformPartsattributeById(zsyhPartsQrcodeHistory.getAttributeId());
            if(EmptyUtils.isNotEmpty(zsyhPlatformPartsattribute.getAttributeInstall())){
                zsyhPartsQrcode.setDeadlineDate(DateUtils.addMonths(date,Integer.parseInt(zsyhPlatformPartsattribute.getAttributeInstall())));
            }
            zsyhPartsQrcode.setPayPrice(zsyhPartsQrcodeHistory.getPayPrice());
            zsyhPartsQrcode.setQrcodeSort(zsyhPartsQrcodeHistory.getApplyNum());
            zsyhPartsQrcodeService.insertZsyhPartsQrcode(zsyhPartsQrcode);
        }
        return new AjaxResult(AjaxResult.Type.SUCCESS,"保存成功",zsyhPartsQrcodeHistory);
    }


    //下载二维码文件
    @CrossOrigin
    @RequiresPermissions("zsyh:qrcodeHistory:list")
    @Log(title = "代码生成", businessType = BusinessType.GENCODE)
    @GetMapping("/downloadExcelPrint")
    public void downloadExcelPrint(String attributeId,String qrCode,long applyNum,HttpServletResponse response) throws IOException {
        String qrCodeFirst = qrCode.substring(0,15);
        Long qrCodeAfter = Long.valueOf(qrCode.substring(15));
        Long codeNum = Long.valueOf(qrCode.substring(16,19) + qrCode.substring(25,30));
        ZsyhPlatformPartsattribute zsyhPlatformPartsattribute = zsyhPlatformPartsattributeService.selectZsyhPlatformPartsattributeById(attributeId);
        // 每次写100行数据，就刷新数据出缓存
        XSSFWorkbook wb = new XSSFWorkbook(); // keep 100 rows in memory,
        Sheet sh = wb.createSheet();
        // 这个是业务数据
        String[] titles = {"序号", "二维码编码", "编码值", "生成时间", "产品编码", "产品名称", "配件型号", "损坏赔付金额"};
        Row row = sh.createRow(0);
        // 第一行设置标题
        for (int i = 0; i < titles.length; i++) {
            String title = titles[i];
            Cell cell1 = row.createCell(i);
            cell1.setCellValue(title);
        }
        // 导出数据
        for (int rowNum = 0; rowNum < applyNum; rowNum++) {

            Row rowData = sh.createRow(rowNum + 1);
            // TbClass 这个是我的业务类，这个是根据业务来进行填写数据
            // 第一列
            Cell cellDataA = rowData.createCell(0);
            cellDataA.setCellValue(rowNum + 1);
            // 第二列
            Cell cellDataB = rowData.createCell(1);

            if(rowNum > 0){
                qrCodeAfter ++;
                codeNum ++;
            }
            qrCode = qrCodeFirst + qrCodeAfter;
            cellDataB.setCellValue("https://xcx.zzzsyh.com/index.html?qrcode=" + qrCode);
            // 第三列
            Cell cellDataC = rowData.createCell(2);
            cellDataC.setCellValue(String.valueOf(codeNum));

            // 第四列
            Cell cellDataD = rowData.createCell(3);
            cellDataD.setCellValue(DateUtils.getDate());

            // 第五列
            Cell cellDataE = rowData.createCell(4);
            cellDataE.setCellValue(zsyhPlatformPartsattribute.getPartsNumber());
            // 第六列
            Cell cellDataF = rowData.createCell(5);
            cellDataF.setCellValue(zsyhPlatformPartsattribute.getPartsName());
            // 第七列
            Cell cellDataG = rowData.createCell(6);
            cellDataG.setCellValue(zsyhPlatformPartsattribute.getAttributeName());
            // 第八列
            if(EmptyUtils.isNotEmpty(zsyhPlatformPartsattribute.getAttributePayPrice())){
                Cell cellDataL = rowData.createCell(7);
                cellDataL.setCellValue(String.valueOf(zsyhPlatformPartsattribute.getAttributePayPrice()));
            }else{
                Cell cellDataL = rowData.createCell(7);
                cellDataL.setCellValue(0);
            }

        }

        String fileName = "二维码数据.xlsx";
        response.reset();
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        wb.write(response.getOutputStream());
        wb.close();

    }

    /**
     * 修改产品二维码申请记录
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        ZsyhPartsQrcodeHistory zsyhPartsQrcodeHistory = zsyhPartsQrcodeHistoryService.selectZsyhPartsQrcodeHistoryById(id);
        mmap.put("zsyhPartsQrcodeHistory", zsyhPartsQrcodeHistory);
        return prefix + "/edit";
    }

    /**
     * 修改保存产品二维码申请记录
     */
    @RequiresPermissions("zsyh:qrcodeHistory:edit")
    @Log(title = "产品二维码申请记录", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ZsyhPartsQrcodeHistory zsyhPartsQrcodeHistory)
    {
        return toAjax(zsyhPartsQrcodeHistoryService.updateZsyhPartsQrcodeHistory(zsyhPartsQrcodeHistory));
    }

    /**
     * 删除产品二维码申请记录
     */
    @RequiresPermissions("zsyh:qrcodeHistory:remove")
    @Log(title = "产品二维码申请记录", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        //判断是否有二维码生成数据，如果已经有了则不能删除
        ZsyhPartsQrcodeHistory zsyhPartsQrcodeHistory = zsyhPartsQrcodeHistoryService.selectZsyhPartsQrcodeHistoryById(ids);
        String qrcode = zsyhPartsQrcodeHistory.getQrcodeFirst();
        int count = zsyhPartsQrcodeService.selectCount(qrcode);
        if(count >1){
            return error("已经存在安装数据，不能删除");
        }else{
            return toAjax(zsyhPartsQrcodeHistoryService.deleteZsyhPartsQrcodeHistoryByIds(ids));
        }
    }

    public String getRandomCode() {
        char[] randomChar = {'1', '2', '3', '4', '5', '6', '7', '8', '9'};
        Random random = new Random();
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < 6; i++) {
            stringBuffer.append(randomChar[Math.abs(random.nextInt()) % randomChar.length]);
        }
        return stringBuffer.toString();
    }

    public int nextInt(int min, int max){
        Random rand= new Random();
        int tmp = Math.abs(rand.nextInt());
        return tmp % (max - min + 1) + min;
    }
}
